package root

import (
	"errors"
	"github.com/gin-gonic/gin"
	log "github.com/star-find-cloud/star-chat/pkg/logger"
	"github.com/star-find-cloud/star-chat/root/domain"
	"github.com/star-find-cloud/star-chat/root/dto"
	"github.com/star-find-cloud/star-chat/root/service"
	"github.com/star-find-cloud/star-chat/utils"
	"net/http"
)

type RootHandler struct {
	srv domain.RootService
}

func NewRootHandler(srv domain.RootService) RootHandler {
	return RootHandler{srv: srv}
}

// Register 系统超级管理员注册请求
// @Summary      系统超级管理员注册接口
// @Description  通过提交注册信息创建新的系统超级管理员账户，成功注册后返回认证令牌
// @Tags         root
// @Accept       json
// @Produce      json
// @Param        request body dto.RegisterReq true "注册请求参数"
// @Success      200 {object} dto.RegisterResp "注册成功，返回令牌"
// @Failure      400 {string} string "请求参数无效或验证码错误"
// @Failure      500 {string} string "服务内部错误"
// @Router       /root/register [post]
func (h *RootHandler) Register(c *gin.Context) {
	var req dto.RegisterReq
	if err := c.ShouldBindJSON(req); err != nil {
		log.AppLogger.Errorf("Failed to parse request body, err: %v", err)
		utils.RespondError(c, http.StatusBadRequest, "request is invalid")
	}

	var root = &domain.Root{
		Name:        req.Name,
		Password:    req.Password,
		Department:  req.Department,
		Position:    req.Position,
		IDCard:      req.IDCard,
		CountryCode: req.CountryCode,
		Phone:       req.Phone,
		Email:       req.Email,
		Level:       req.Level,
	}

	token, err := h.srv.Register(c, root, req.VerificationCode)
	if err != nil {
		var srvErr *service.SrvError
		if errors.As(err, &srvErr) {
			switch srvErr.Code {
			case service.CodeInvalidObject:
				utils.RespondError(c, http.StatusBadRequest, "request is invalid")
			case service.CodeInternalError:
				utils.RespondError(c, http.StatusInternalServerError, "Busy service")
			}
		}
	}
	utils.RespondJSON(c, http.StatusOK, &dto.RegisterResp{token})
	return
}
